'''
Created on 2018年2月12日

@author: wesley.wei
'''
# -*- encoding=UTF-8 -*-
from fileTest.BinaryRecordFile import BinaryRecordFile
import struct

class Bike:
    def __int__(self,identity,name,quantity,price):
        assert len(identity) > 3, ("invalid bike id '{0}'".format(identity))
        self.__identity = identity
        self.__name = name
        self.__quantity = quantity
        self.__price = price
    
    def print(self):
        print("this bike is {0}".format(self.__identity))


_BIKE_STRUCT = struct.Struct("<8s30sid")
class BikeStock:
    
    def __init__(self, filename):
        self.__file = BinaryRecordFile(self,filename,_BIKE_STRUCT.size)
        self.__index_from_identity = {}
        for index in range(len(self.__file)):
            record = self.__file[index]
            if record is not None:
                bike = self._bike_from_record(self,record)
                self.__index_from_identity[bike.identity] = index
    
    
    def append(self, bike):
        index = len(self.__file)
        self.__file[index] = self._record_from_bike(self,bike)
        self.__index_from_identity[bike.identity] = index
    
    def __getitem__(self, identity):
        record = self.__file[self.__index_from_identity[identity]]
        return None if record is None else self._bike_from_record(self,record)
    
    
    def __change_stock(self, identity, amount):
        index = self.__index_from_identity[identity]
        record = self.__file[index]
        if record is None:
            return False
        bike = self._bike_from_record(self,record)
        bike.quantity += amount
        self.__file[index] = self._record_from_bike(self,bike)
        return True
    
        increase_stock = (lambda self, identity, amount:
                                     self.__change_stock(identity, amount))
        decrease_stock = (lambda self, identity, amount:
                                     self.__change_stock(identity, -amount))
    
    def __iter__(self):
        for index in range(len(self.__file)):
            record = self.__file[index]
            if record is not None:
                yield self._bike_from_record(self,record)
                

    def _bike_from_record(self,record):
        ID, NAME, QUANTITY, PRICE = range(4)
        parts = list(_BIKE_STRUCT.unpack(record))
        parts[ID] = parts[ID].decode("utf8").rstrip("\x00")
        parts[NAME] = parts[NAME].decode("utf8").rstrip("\x00")
        return Bike(*parts)
    
    def _record_from_bike(self,bike):
        return _BIKE_STRUCT.pack(bike.identity.encode("utf8"),
                                   bike.name.encode("utf8"),
                                   bike.quantity, bike.price)
    
    